import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
// toast定时器
let toastTimer = null;
export default new Vuex.Store({
  state: {
    toast: {
      show: false,
      type: '',
      text: '',
      delay: 2000,
    },
    loading: {
      show: false,
      text: '',
    },
  },
  getters: {
    getToast(state) {
      return state.toast;
    },
    getLoading(state) {
      return state.loading;
    },
  },
  mutations: {
    showToast(state, payload) {
      state.toast.show = true;
      if (typeof payload === 'string') state.toast.text = payload;
      else if (typeof payload === 'object') {
        state.toast.text = payload.text || '';
        state.toast.type = payload.type || '';
        state.toast.delay = payload.delay || 2000;
      }
    },
    hideToast(state) {
      state.toast.show = false;
      state.toast.text = '';
      state.toast.type = '';
    },
    showLoading(state, text) {
      state.loading.show = true;
      state.loading.text = text || 'Loading…';
    },
    hideLoading(state) {
      state.loading.show = false;
      state.loading.text = '';
    },
  },
  actions: {
    showToast({ state, commit }, playload) {
      commit('showToast', playload);
      if (toastTimer) clearTimeout(toastTimer);
      toastTimer = setTimeout(() => {
        commit('hideToast');
      }, state.toast.delay);
    },
  },
});
